<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        list-style: none;
      }
    </style>
  </head>
  <body>
    <input type="text" name="" id="ipt" />
    <ul>
      <!-- <li>
        <span></span>
        <button>删除</button>
      </li> -->
    </ul>
    <button class="btn">全部删除</button>
    <script>
      let url = "http://localhost:3000/todos";
      function loadList() {
        let xhr = new XMLHttpRequest();
        xhr.open("get", url);
        xhr.setRequestHeader("content-type", "application/json");
        xhr.send();
        xhr.onload = function () {
          if (xhr.status == 200) {
            let obj = JSON.parse(xhr.responseText);
            console.log(obj);
            document.querySelector("ul").innerHTML = obj
              .map(
                (v) => `<li>
                          <input ${
                            v.completed ? "checked" : ""
                          } type="checkbox" class="com" data-id="${
                  v.id
                }" data-com ="${v.completed}">
                            <span>${v.title}</span>
                            <button class="del" data-id="${v.id}">删除</button>
                        </li>`
              ) //data-com ="${v.completed}"可以拿到复选框以前的状态,字符串类型
              .reverse()
              .join("");
            //--可以获取所有的删除按钮-添加点击事件
          }
        };
      }

      loadList();

      let ipt = document.querySelector("#ipt");
      ipt.onkeydown = function (e) {
        if (e.keyCode == 13) {
          //发布--发布完-刷新列表
          let title = ipt.value;
          let completed = false;
          let bodyObj = { title, completed };
          let xhr = new XMLHttpRequest();
          xhr.open("POST", url);
          xhr.setRequestHeader("content-type", "application/json");
          //   xhr.send('{"title":"aa"}');
          xhr.send(JSON.stringify(bodyObj));
          xhr.onload = function () {
            // 异步执行的
            if (xhr.status == 201) {
              let obj = JSON.parse(xhr.responseText);
              console.log(obj);

              // 想要让两个异步操作有顺序--就必须嵌套
              // 第二个操作，写到第一个异步操作成功的回调函数里面
              loadList();
              ipt.value = "";
              //
            }
          };
          // 同时发起了两个异步操作--谁先成功-不一定的

          // loadList();

          console.log(1);
          console.log(2);
        }
      };

      // 事件委托--给btn添加点击事件
      // 利用事件冒泡的特点-直接给父元素添加点击事件，子元素的事件会冒泡给父元素
      // 好处：效率高，可以给未来的元素添加事件
      let ul = document.querySelector("ul");
      ul.onclick = function (e) {
        console.log(e);
        if (e.target.className == "del") {
          console.log("点击了删除按钮");

          // 获取所有data-xx 开头自定义属性
          // data-id
          // data-username
          // {id:1,username}
          console.log(e.target.dataset);
          console.log(e.target.dataset.id);
          let todoId = e.target.dataset.id;
          // 调用删除接口--需要todo的id
          // http://localhost:3000/todos/:id
          let delAPI = url + "/" + todoId;
          let xhr = new XMLHttpRequest();
          xhr.open("DELETE", delAPI);
          xhr.setRequestHeader("content-type", "application/json");
          xhr.send();
          xhr.onload = function () {
            if (xhr.status == 200) {
              let obj = JSON.parse(xhr.responseText);
              console.log(obj);
              //删除成功--刷新列表或者页面
              // location.reload()
              loadList();
            }
          };
        } else if (e.target.className == "com") {
          console.log("点击了checkbox");
          //获取需要修改的值的ID
          // console.log(e.target.dataset);
          // console.log(e.target.dataset.id);
          let todoId = e.target.dataset.id;
          // console.log(e.target.checked); //可以拿到复选框现在的状态,布尔类型
          // let com = e.target.dataset.com;
          // console.log(com);
          let xhr = new XMLHttpRequest();
          xhr.open("PATCH", url + "/" + id);
          xhr.setRequestHeader("content-type", "application/json");
          let body = { completed: e.target.checked };
          xhr.send(JSON.stringify(body));
          xhr.onload = function () {
            if (xhr.status == 200) {
              let obj = JSON.parse(xhr.responseText);
              console.log(obj);
            }
          };
        }
      };
      let oBtn = document.querySelector(".btn");
      oBtn.onclick = function (e) {
        let todos = Array.from(
          e.target.previousSibling.previousSibling.children
        );
        console.log(todos);
        if (todos.length == 0) {
          alert("没有可删除的");
          return;
        }
        if (!confirm("确定全部删除吗")) {
          return;
        }
        for (let j = 0; j < todos.length; j++) {
          // console.log(todos[j].firstElementChild.dataset);
          let todoId = todos[j].firstElementChild.dataset.id;
          // console.log(todoId);
          let delAPI = url + "/" + todoId;
          let xhr = new XMLHttpRequest();
          xhr.open("DELETE", delAPI);
          xhr.setRequestHeader("content-type", "application/json");
          xhr.send();
          xhr.onload = function () {
            if (xhr.status == 200) {
              let obj = JSON.parse(xhr.responseText);
              console.log(obj);
              loadList();
            }
          };
        }
      };
    </script>
  </body>
</html>
